package com.ruoyi.web.service.Impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.web.domain.vo.InventoryVo;
import com.ruoyi.web.domain.vo.MesInventoryInfoVo;
import com.ruoyi.web.domain.vo.StatVo;
import com.ruoyi.web.mapper.MesConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.domain.MesInventoryDetail;
import com.ruoyi.web.mapper.MesInventoryInfoMapper;
import com.ruoyi.web.domain.MesInventoryInfo;
import com.ruoyi.web.service.IMesInventoryInfoService;

import javax.annotation.Resource;

/**
 * 盘点Service业务层处理
 *
 * @author wxt
 * @date 2024-01-24
 */
@Service
public class MesInventoryInfoServiceImpl implements IMesInventoryInfoService {
    @Resource
    private MesInventoryInfoMapper mesInventoryInfoMapper;

    @Resource
    private MesConfigMapper configMapper;

    /**
     * 查询盘点
     *
     * @param id 盘点主键
     * @return 盘点
     */
    @Override
    public MesInventoryInfo selectMesInventoryInfoById(Long id) {
        return mesInventoryInfoMapper.selectMesInventoryInfoById(id);
    }

    /**
     * 查询盘点列表
     *
     * @param mesInventoryInfo 盘点
     * @return 盘点
     */
    @Override
    public List<MesInventoryInfo> selectMesInventoryInfoList(MesInventoryInfo mesInventoryInfo) {
        return mesInventoryInfoMapper.selectMesInventoryInfoList(mesInventoryInfo);
    }
    @Override
    public List<MesInventoryInfoVo> selectMesInventoryDetailList(MesInventoryInfo mesInventoryInfo){
        List<String> yearMonths = new ArrayList<>();
        if(StringUtils.isNotEmpty(mesInventoryInfo.getStartDate()) && StringUtils.isNotEmpty(mesInventoryInfo.getEndDate())) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate sDate = LocalDate.parse(mesInventoryInfo.getStartDate(), formatter);
            LocalDate eDate = LocalDate.parse(mesInventoryInfo.getEndDate(), formatter);
            LocalDate startDate = LocalDate.of(sDate.getYear(), sDate.getMonthValue(), sDate.getDayOfMonth());
            LocalDate endDate = LocalDate.of(eDate.getYear(), eDate.getMonthValue(), eDate.getDayOfMonth());
            LocalDate currentDate = startDate;
            while (!currentDate.isAfter(endDate)) {
                String yearMonth = String.format("%d-%02d", currentDate.getYear(), currentDate.getMonthValue());
                yearMonths.add(yearMonth);
                currentDate = currentDate.plus(1, ChronoUnit.MONTHS);
            }
        }
        if(yearMonths.size()>0){ //盘点日期
            String inventoryMonth=String.join(",",yearMonths);
            mesInventoryInfo.setInventoryMonth(inventoryMonth);
        }
        List<MesInventoryInfoVo> list =mesInventoryInfoMapper.selectMesInventoryDetail(mesInventoryInfo);
        if(list.size()>0){
            MesInventoryInfoVo vo =mesInventoryInfoMapper.selectMesInventoryDetailSum(mesInventoryInfo);
            list.get(0).setProfitLossSum(vo.getProfitLossSum());
        }
        return list;
    }

    @Override
    public List<InventoryVo> selectMesDetaillist(MesInventoryInfo mesInventoryInfo) {
        List<InventoryVo> data = mesInventoryInfoMapper.selectMesDetaillist(mesInventoryInfo);
        return data;
    }


    @Override
    public Date selectRecently(String machineId) {
        return mesInventoryInfoMapper.selectRecently(machineId);
    }

    @Override
    public List<InventoryVo> selectDayInventory(MesInventoryInfo mesInventoryInfo) {
        return mesInventoryInfoMapper.selectDayInventory(mesInventoryInfo);
    }

    /**
     * 新增盘点
     *
     * @param mesInventoryInfo 盘点
     * @return 结果
     */
    @Transactional
    @Override
    public int insertMesInventoryInfo(MesInventoryInfo mesInventoryInfo) {
        mesInventoryInfo.setCreateTime(DateUtils.getNowDate());

        // 生成盘点单编号
//        int maxNum = mesInventoryInfoMapper.selectMaxId();

        Map<String, Object> map = new HashMap<>();
        map.put("columnName", "inventory_num");
        map.put("tableName", "mes_inventory_info");
        int maxNum = configMapper.getMaxId(map);

        String code = PinYinUtils.getCodeNormal(maxNum, "ZZPDD");
        mesInventoryInfo.setInventoryNum(code);

        int rows = mesInventoryInfoMapper.insertMesInventoryInfo(mesInventoryInfo);
        insertMesInventoryDetail(mesInventoryInfo);
        return rows;
    }

    /**
     * 修改盘点
     *
     * @param mesInventoryInfo 盘点
     * @return 结果
     */
    @Transactional
    @Override
    public int updateMesInventoryInfo(MesInventoryInfo mesInventoryInfo) {
        int status = mesInventoryInfo.getStatus();
        if (status == 2) {//已提交
          //修改机台库存或者纸库库存
          if(mesInventoryInfo.getInventoryStore().equals("0")){ //修改纸库库存
              mesInventoryInfoMapper.updatePaperQuantity(mesInventoryInfo);
          }else{ //修改机台纸张库存
              mesInventoryInfoMapper.updateMachinePaperQuantity(mesInventoryInfo);
          }
        } else {
            mesInventoryInfoMapper.deleteMesInventoryDetailByInventoryid(mesInventoryInfo.getId());
            insertMesInventoryDetail(mesInventoryInfo);
        }
        return mesInventoryInfoMapper.updateMesInventoryInfo(mesInventoryInfo);
    }

    /**
     * 批量删除盘点
     *
     * @param ids 需要删除的盘点主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesInventoryInfoByIds(Long[] ids) {
        mesInventoryInfoMapper.deleteMesInventoryDetailByInventoryids(ids);
        return mesInventoryInfoMapper.deleteMesInventoryInfoByIds(ids);
    }

    /**
     * 删除盘点信息
     *
     * @param id 盘点主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteMesInventoryInfoById(Long id) {
        mesInventoryInfoMapper.deleteMesInventoryDetailByInventoryid(id);
        return mesInventoryInfoMapper.deleteMesInventoryInfoById(id);
    }

    /**
     * 新增盘点明细信息
     *
     * @param mesInventoryInfo 盘点对象
     */
    public void insertMesInventoryDetail(MesInventoryInfo mesInventoryInfo) {
        List<MesInventoryDetail> mesInventoryDetailList = mesInventoryInfo.getMesInventoryDetailList();
        Long id = mesInventoryInfo.getId();
        if (StringUtils.isNotNull(mesInventoryDetailList)) {
            List<MesInventoryDetail> list = new ArrayList<MesInventoryDetail>();
            for (MesInventoryDetail mesInventoryDetail : mesInventoryDetailList) {
                mesInventoryDetail.setInventoryid(id);
                list.add(mesInventoryDetail);
            }
            if (list.size() > 0) {
                mesInventoryInfoMapper.batchMesInventoryDetail(list);
            }
        }
    }


    //不选择仓库或者机台
    @Transactional
    @Override
    public List<StatVo> wareMachineByPaper(MesInventoryInfo inventory){
        List<StatVo> list = new ArrayList<>();
        Map<String, Object> params = inventory.getParams();
        PageHelper.startPage(inventory.getPageNum(), inventory.getPageSize());
        list= mesInventoryInfoMapper.wareMachineByPaper(inventory);
        return list;
    }

    //白纸裁切组统计
    @Transactional
    @Override
    public List<StatVo> cuttingGroupsStat(MesInventoryInfo inventory){
        List<StatVo> list = new ArrayList<>();
        PageHelper.startPage(inventory.getPageNum(), inventory.getPageSize());
        list = mesInventoryInfoMapper.cuttingGroupStat(inventory);
        return list;
    }


    //纸库统计
    @Transactional
    @Override
    public List<StatVo> warehousestat(MesInventoryInfo inventory) {
        List<StatVo> list = new ArrayList<>();
        Map<String, Object> params = inventory.getParams();
        MesInventoryInfo data = mesInventoryInfoMapper.selectFinal(inventory);//按日期查询盘点最后一条

        if(inventory.getInventoryDate()==null) {
            LocalDateTime defaultLocalDateTime = LocalDateTime.parse("1900-01-01 00:00:00");
            // 转换为Date类型
            Date invetorydate = Date.from(defaultLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());
            inventory.setInventoryDate(invetorydate);
        }

        if (data == null) {
        //    throw new ServiceException("没有获得盘点数据，无法进行统计");
            PageHelper.startPage(inventory.getPageNum(), inventory.getPageSize());
            list = mesInventoryInfoMapper.warehousestatNot(inventory);
            return list;
        }

        inventory.setId(data.getId());
//        inventory.setInventoryDate(data.getInventoryDate());

        // PageHelper.startPage((Integer) params.get("pageNum"), (Integer) params.get("pageSize"));
        PageHelper.startPage(inventory.getPageNum(), inventory.getPageSize());
        list = mesInventoryInfoMapper.warehousestat(inventory);
        return list;
    }

    //机台统计
    @Transactional
    @Override
    public List<StatVo> machinestat(MesInventoryInfo Inventory) {
        List<StatVo> list = new ArrayList<>();
        Map<String, Object> params = Inventory.getParams();

        MesInventoryInfo data = mesInventoryInfoMapper.selectMachineFinal(Inventory);

        if(Inventory.getInventoryDate()==null) {
            LocalDateTime defaultLocalDateTime = LocalDateTime.parse("1900-01-01 00:00:00");
            // 转换为Date类型
            Date invetorydate = Date.from(defaultLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());
            Inventory.setInventoryDate(invetorydate);
        }

        if (data == null) {
            Inventory.setInventoryStore(Inventory.getMachineId());
            //  throw new ServiceException("没有获得盘点数据，无法进行统计");
////            return list;
            PageHelper.startPage(Inventory.getPageNum(), Inventory.getPageSize());
            list = mesInventoryInfoMapper.machinestatNot(Inventory);
        } else {
            Inventory.setId(data.getId());
//            Inventory.setInventoryDate(data.getInventoryDate());
            Inventory.setInventoryStore(data.getInventoryStore());

            // PageHelper.startPage((Integer) params.get("pageNum"), (Integer) params.get("pageSize"));
            PageHelper.startPage(Inventory.getPageNum(), Inventory.getPageSize());
            list = mesInventoryInfoMapper.machinestat(Inventory);
        }
        return list;
    }

}
